<template>
  <div class="inventory-page">
    <!-- 数据筛选 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-title">数据筛选</div>
      <el-form :inline="true" :model="filter" class="filter-form">
        <el-form-item label="盘点单号：">
          <el-input v-model="filter.StocktakingId" placeholder="请输入/扫描单号" clearable style="width: 180px;" />
        </el-form-item>
        <el-form-item label="起始时间：">
          <el-date-picker v-model="filter.OrderCreatorTime" type="date" placeholder="起始时间" style="width: 150px;" />
        </el-form-item>
        <el-form-item label="单据状态：">
          <el-select v-model="filter.State" placeholder="请选择" style="width: 120px;">
            <el-option v-for="opt in statusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="ShowInventory"><el-icon>
              <Search />
            </el-icon>查询</el-button>
          <el-button @click="handleReset"><el-icon>
              <Refresh />
            </el-icon>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据列表操作栏 -->
    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <span class="table-title">数据列表</span>
        <div class="table-actions">
          <el-button type="primary" size="small" icon="Plus" @click="handleAdd">新增</el-button>
          <el-button size="small" icon="Edit">编辑</el-button>
          <el-button size="small" icon="Delete">删除</el-button>
          <el-button size="small" icon="Download">导出</el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%; margin-top: 10px;">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="stocktakingId" label="盘点单号" width="120" />
        <el-table-column prop="stocktakingType" label="盘点类型" width="120">
          <template #default="scope">
            <span v-if="scope.row.stocktakingType == 0">产品盘点</span>
            <span v-if="scope.row.stocktakingType == 1">产品盘点</span>
            <span v-if="scope.row.stocktakingType == 2">产品盘点</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderNumber" label="关联单号" width="120" />
        <el-table-column prop="state" label="状态" width="120">
          <template #default="scope">
            <span v-if="scope.row.state == 0">等待审核</span>
            <span v-if="scope.row.state == 1">审核成功</span>
            <span v-if="scope.row.state == 2">审核失败</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderCreator" label="制单人" width="120" />
        <el-table-column prop="orderCreatorTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-link type="primary" :underline="false">查看</el-link>
            <el-link type="primary" :underline="false" style="margin-left: 8px;" @click="handleEdit(scope.row)">编辑</el-link>
            <el-link type="primary" @click="DelInventory(scope.row.id)" :underline="false"
              style="margin-left: 8px;">删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作栏和分页 -->
      <div class="table-footer">
        <div class="batch-actions">
          <el-button size="small">全选</el-button>
          <el-button size="small">反选</el-button>
          <el-select size="small" placeholder="批量操作" style="width: 120px;">
            <el-option label="批量删除" value="delete" />
            <el-option label="批量导出" value="export" />
          </el-select>
        </div>
        <div class="demo-pagination-block">
          <el-pagination v-model:current-page="Total.PageIndex" v-model:page-size="Total.PageSize"
            :page-sizes="[15, 30, 45, 60]" :size="size" :disabled="disabled" :background="background"
            layout="total, sizes, prev, pager, next, jumper" :total="Total.totalCount" />
        </div>
      </div>
    </el-card>

    <!-- 新增盘点单弹窗 -->
    <el-dialog v-model="dialogVisible" title="新增盘点单" width="900px" :close-on-click-modal="false" class="custom-dialog">
      <div class="dialog-section-title">基本信息</div>
      <el-form :model="addForm" label-width="90px" class="custom-form">
        <el-row :gutter="20">
          <el-col :span=12>
            <el-form-item label="盘点单号">
              <el-input v-model="addForm.stocktakingId" placeholder="可不填写，自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span=12>
            <el-form-item label="关联订单号">
              <el-input v-model="addForm.orderNumber" />
            </el-form-item>
          </el-col>
          <el-col :span=12>
            <el-form-item label="制单人">
              <el-input v-model="addForm.orderCreator" />
            </el-form-item>
          </el-col>
          <el-col :span=12>
            <el-form-item label="制单时间">
              <el-date-picker 
                v-model="addForm.orderCreatorTime"
                type="datetime"
                value-format="YYYY-MM-DDTHH:mm:ss.fffZ"
                placeholder="请选择制单时间"
              />
              </el-form-item>
          </el-col>
          <el-col :span=24>
            <el-form-item label="备注">
              <el-input type="textarea" v-model="addForm.note" :maxlength="300" show-word-limit placeholder="请输入备注信息"
                :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider />
      <div class="dialog-section-title">产品信息</div>
      <div style="text-align: right; margin-bottom: 10px;">
        <el-button type="primary" size="small" icon="Plus" @click="handleAddProduct">新增产品</el-button>
      </div>
      <el-table :data="addForm.products" border style="width: 100%; margin-bottom: 20px;">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="productName" label="产品名称" width="120" align="center" />
        <el-table-column prop="productCode" label="产品编码" width="100" align="center" />
        <el-table-column prop="spec" label="规格" width="100" align="center" />
        <el-table-column prop="batchNo" label="批次" width="100" align="center" />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="location" label="库位" width="180" align="center" />
        <el-table-column label="操作" width="80" align="center">
          <template #default="scope">
            <el-link type="danger" @click="handleDeleteProduct(scope.$index)">
              <el-icon>
                <Delete />
              </el-icon>删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
// 移除重复导入的组件，保留统一导入
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete, Download } from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'
import type { ComponentSize } from 'element-plus'
import http from '@/http/axiosHelper'
onMounted(() => {
  ShowInventory();
})
const filter = ref({
  StocktakingId: '',
  OrderCreatorTime: '',
  State: ''
})
const statusOptions = [
  { label: '请选择', value: '' },
  { label: '等待审核', value: '0' },
  { label: '审核成功', value: '1' },
  { label: '审核失败', value: '2' }
]
const Total = ref({
  PageSize: 15,
  PageIndex: 1,
  totalPage: 1,
  totalCount: 1
})
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
watch(Total, () => {
  ShowInventory()
}, { deep: true })
const tableData = ref([])
const ShowInventory = () => {
  http.get("/lssueread/api/Stocktaking/GetStocktaking", {
    params: {
      PageSize: Total.value.PageSize,
      PageIndex: Total.value.PageIndex,
      StocktakingId: filter.value.StocktakingId,
      OrderCreatorTime:filter.value.OrderCreatorTime,
      State: filter.value.State
    }
  }).then(res => {
    tableData.value = res.data.pageDatas
    Total.value.totalCount = res.data.totalCount
    Total.value.totalPage = res.data.totalPage
  })
}
function handleReset() {
  filter.value = { StocktakingId: '', OrderCreatorTime: '', State: '' }
}
const DelInventory = (id: any) => {
  ElMessageBox.confirm(
    '此操作将永久删除该数据，是否继续？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      http.get("/lssuewrite/api/Stocktaking/DelStocktaking", {
        params: { Id: id }
      }).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message)
          ShowInventory()
        } else {
          ElMessage.warning(res.data.message)
        }
      })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}
const dialogVisible = ref(false)
const addForm = ref({
  stocktakingId: '',
  stocktakingType: 1,
  orderNumber: '',
  orderCreator: '',
  orderCreatorTime: '',
  note: '',
  products: [] as any[]
})
const handleAdd = () => {
  // 生成当前时间的盘点单号（只包含时分秒）
  const now = new Date();
  const pad = (n: number) => n.toString().padStart(2, '0');
  const stocktakingId = 
    pad(now.getHours()) + 
    pad(now.getMinutes()) + 
    pad(now.getSeconds());
  // 重置表单数据 - 修改为直接修改属性而非替换对象
  addForm.value.stocktakingId = stocktakingId;
  addForm.value.stocktakingType = 1;
  addForm.value.orderNumber = '';
  addForm.value.orderCreator = '';
  addForm.value.orderCreatorTime = '';
  addForm.value.note = '';
  // 显式清空产品列表
  addForm.value.products = [];
  dialogVisible.value = true;
}
const handleSubmit = () => {
  // 保留原有表单结构，仅调整提交时的数据映射
  const submitData = {
    ...addForm.value,
    // 补充接口必填字段
    state: 0,
    reviewer: '',
    reviewertime: ''
  }
  
  // 产品列表字段映射
  submitData.products = addForm.value.products.map(item => ({
    productid: item.productId || 0,
    productCode: item.productCode,
    quantity: item.quantity,
    batchNo: item.batchNo,
    createtime: new Date().toISOString()
  }))

  http.post("/lssuewrite/api/Stocktaking/CreateStocktaking", submitData).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.message)
      dialogVisible.value = false
      ShowInventory()
    } else {
      ElMessage.warning(res.data.message)
    }
  })
}
const handleAddProduct = () => {
  addForm.value.products.push({
    productName: '',
    productCode: '',
    spec: '',
    batchNo: '',
    unit: '',
    location: ''
  })
}
const handleDeleteProduct = (index: number) => {
  addForm.value.products.splice(index, 1)
}
const handleEdit = async (row: any) => {
  // 回填基本信息
  addForm.value = {
    stocktakingId: row.stocktakingId,
    stocktakingType: row.stocktakingType,
    orderNumber: row.orderNumber,
    orderCreator: row.orderCreator,
    orderCreatorTime: row.orderCreatorTime,
    note: row.note,
    products: []
  }
  // 查询产品信息
  const res = await http.get("/lssueread/api/Stocktaking/GetStocktakingProduct", {
    params: { StocktakingId: row.stocktakingId }
  });
  addForm.value.products = (res.data.data || []).map((item: any) => ({
    productName: item.productName,
    productCode: item.productCode,
    spec: item.specifications,
    batchNo: item.batchNo || '', // 如果有批次字段
    unit: item.unitName,
    location: item.locationName
  }));
  dialogVisible.value = true;
}
</script>

<style scoped>
.inventory-page {
  background: #f5f6fa;
  min-height: 100vh;
  padding: 20px;
}

.filter-card {
  margin-bottom: 18px;
}

.filter-title {
  font-weight: bold;
  font-size: 15px;
  margin-bottom: 8px;
}

.filter-form {
  margin-top: 8px;
}

.table-card {
  padding-bottom: 0;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
}

.table-title {
  font-weight: bold;
  font-size: 15px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 美化新增盘点单弹窗 */
.custom-dialog .el-dialog__body {
  background: #f8fafc;
  border-radius: 8px;
  padding-top: 18px;
  padding-bottom: 10px;
}

.dialog-section-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}

.custom-form .el-form-item {
  margin-bottom: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-table th,
.el-table td {
  text-align: center;
}
</style>
